/*
 * C/C++ KLIB Project
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include "klib.h"
#include <windows.h>

void quicksort(void *base, void *(*get_element)(void *, int), int left, int right, int (*compare)(const void *, const void *), void (*swap)(void *, int, int))
{
	void *pivot;
	int x, i, r, n, mid;

	if (right > left && left >= 0) {
		if (right < left + 8) {
			insertsort(base, get_element, left, right, compare, swap);
		}
		else {
			mid = (right + left + 1) / 2;
			mid = midx(base, left, mid, right, get_element, compare);
			if (mid != left) {
				swap(base, left, mid);
			}
			
			pivot = get_element(base, left);
			x = right;
			n = 0;

			for (i = right; i > left; i--) {
				r = compare(get_element(base, i), pivot);
				if (r > 0) {
					swap(base, i, x--);
				}
				else if (r == 0) {
					++n;
				}
			}

			if (n == right - left) {
				// all elements are equal
				return;
			}

			if (compare(pivot, get_element(base, x))) {
				swap(base, left, x);
			}

			quicksort(base, get_element, left, x - 1, compare, swap);
			quicksort(base, get_element, x + 1, right, compare, swap);
		}
	}
}

